#!/usr/bin/env python3
"""
Flask项目快速启动脚本
"""
import subprocess
import sys
import os
import json

def check_dependencies_installed():
    """检查依赖是否已安装"""
    try:
        import flask
        import flask_sqlalchemy
        import flask_restx
        import werkzeug
        return True
    except ImportError:
        return False

def install_requirements():
    """安装依赖"""
    print("🔧 正在安装项目依赖...")
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"])
        print("✅ 依赖安装成功!")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ 依赖安装失败: {e}")
        return False

def start_server():
    """启动服务器"""
    print("🚀 正在启动Flask服务器...")
    print("=" * 50)
    print("📱 API接口地址: http://localhost:5000/api/")
    print("📚 API文档地址: http://localhost:5000/api/docs/")
    print("🛑 按 Ctrl+C 停止服务器")
    print("=" * 50)
    
    try:
        # 直接启动应用
        from app import create_app
        app = create_app()
        app.run(host='0.0.0.0', port=5000, debug=True)
    except KeyboardInterrupt:
        print("\n👋 服务器已停止")
    except Exception as e:
        print(f"❌ 启动服务器时出错: {e}")
        import traceback
        traceback.print_exc()

def main():
    print("🎉 Flask项目启动器")
    print("=" * 30)
    
    # 检查必要文件
    required_files = ["requirements.txt", "app/__init__.py"]
    for file in required_files:
        if not os.path.exists(file):
            print(f"❌ 缺少必要文件: {file}")
            return
    
    # 检查依赖是否已安装
    if not check_dependencies_installed():
        print("📦 检测到依赖未安装，正在安装...")
        if not install_requirements():
            print("❌ 依赖安装失败，请手动安装: pip install -r requirements.txt")
            return
    else:
        print("✅ 依赖已安装，跳过安装步骤")
    
    print("\n" + "=" * 30)
    
    # 启动服务器
    start_server()

if __name__ == "__main__":
    main()
